package interview.algorithms.again_in_interview;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author fance
 * @date 2018/7/17 15:41
 */
public class IO {
    public static void copyFile(String src, String dist) throws IOException
    {
        FileInputStream in = new FileInputStream(src);
        FileOutputStream out = new FileOutputStream(dist);
        byte[] buffer = new byte[20 * 1024];
        // read() 最多读取 buffer.length 个字节
        // 返回的是实际读取的个数
        // 返回 -1 的时候表示读到 eof，即文件尾
        while (in.read(buffer, 0, buffer.length) != -1) {
            out.write(buffer);
        }
        in.close();
        out.close();
    }

    public static void fastCopy(String src, String dist) throws IOException {
        FileInputStream fin = new FileInputStream(src);      /* 获取源文件的输入字节流 */
        FileChannel fcin = fin.getChannel();                 /* 获取输入字节流的文件通道 */
        FileOutputStream fout = new FileOutputStream(dist);  /* 获取目标文件的输出字节流 */
        FileChannel fcout = fout.getChannel();               /* 获取输出字节流的通道 */
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while (true) {
            int r = fcin.read(buffer);                       /* 从输入通道中读取数据到缓冲区中 */
            if (r == -1) {                                   /* read() 返回 -1 表示 EOF */
                break;
            }
            buffer.flip();
            fcout.write(buffer);
            buffer.clear();
        }
    }
}
